package czy.demo.config.shiro;

import czy.demo.entity.system.User;
import czy.demo.repository.UserRepository;
import org.apache.shiro.authc.*;
import org.apache.shiro.biz.authz.principal.ShiroPrincipalRepositoryImpl;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Optional;

/* 默认的shiro用户仓库，由AbstractAuthorizingRealm调用 */
@Component
public class DefaultShiroPrincipalRepository extends ShiroPrincipalRepositoryImpl {

    @Autowired
    private UserRepository userRepository;

    /* 使用token获取认证信息方法，登录时调用 */
    @Override
    public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        Optional<User> optional = this.userRepository.findByUsername((String)token.getPrincipal());
        if(optional.isPresent()){
            User user = optional.get();
            /* 返回加盐认证信息 */
            return new SimpleAuthenticationInfo(user,user.getPassword(),new SimpleHash(user.getSalt()),"username-password");
        }
        return null;
    }


}
